<?php
namespace app\mobile\controller\user;
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2017/4/15
 * Time: 11:07
 */
class Login extends \app\mobile\controller\Base
{
    private $mod;
    public function _initialize(){
        parent::_initialize();
        $this->mod = model('user');
    }
    public function index(){
        $usersetting = cache('user');
        $this->setSeo(['title'=>'会员登录']);
        $this->assign('forward',request()->url());
        $this->assign('title','会员登录');
        $this->assign('usersetting',$usersetting);
        return $this->fetch();
    }
    public function reg(){
        $this->setSeo(['title'=>'会员注册']);
        $this->assign('title','会员注册');
        return $this->fetch();
    }
    public function loginDo(){
        $username = input('post.username');
        $password = input('post.password');
        $forward  = input('post.forward');
        $code     = input('post.code');
        if(empty($forward) || strpos($forward,'login')!==FALSE){
            $forward = url('user.index/index');
        }
        $return['status'] = 0;
        if(empty($username)){
            $return['msg'] = '请填写用户名或手机号码';
        }elseif(strlen($password)<6){
            $return['msg'] = '密码至少为6位';
        }elseif(!captcha_check($code)){
            $return['msg'] = '验证码不正确';
        }else{
            $where['username|mobile'] = $username;
            $where['password'] = passwordEncode($password);
            $info = $this->mod->where($where)->field('username,nickname,mobile,model,status,email,id')->find();
            if($info){
                if($info['status'] == 0){
                    $return['msg'] = '账号被冻结，请联系客服！';
                }else{
                    $edit['login_time'] = time();
                    $edit['login_ip']   = request()->ip();
                    $edit['login_num']  = ['exp','login_num+1'];
                    $this->mod->save($edit,['id'=>$info['id']]);
                    $model = $info->getData('model');
                    $info = objToArray($info);
                    $info['model'] = $model;
                    cookie('userInfo',$info);
                    $return['status'] = 1;
                    $return['uri']    = $forward;
                }
            }else{
                $return['msg'] = '账号或密码错误';
            }
        }
        return json($return);
    }
    public function regDo(){
        $username = input('post.username');
        $password = input('post.password');
        $password2 = input('post.repassword');
        $code      = input('post.code');
        $mobile    = input('post.mobile');
        $email     = input('post.email');
        $model = input('post.model/d',1);
        $return['status'] = 0;
        if(cache('user')['register'] == 0){
            $return['msg'] = '网站关闭了注册通道';
        }elseif(empty($username)){
            $return['msg'] = '请填写用户名';
        }elseif(strlen($password)<6){
            $return['msg'] = '密码至少为6位';
        }elseif($password!=$password2){
            $return['msg'] = '两次密码输入不一致！';
        }elseif(!captcha_check($code)){
            $return['msg'] = '验证码不正确';
        }elseif(!is_mobile($mobile)){
            $return['msg'] = '请填写正确的手机号码，将用于密码找回';
        }elseif(!isEmail($email)){
            $return['msg'] = '请填写正确的邮箱';
        }elseif(!$this->checkUser($username,'username')){
            $return['msg'] = '用户名已被注册';
        }elseif(!$this->checkUser($mobile,'mobile')){
            $return['msg'] = '手机号码已被注册';
        }elseif(!$this->checkUser($email,'email')){
            $return['msg'] = '邮箱号码已被注册';
        }else{
            $data['username'] = $data['nickname'] = $username;
            $data['password'] = $password;
            $data['mobile']   = $mobile;
            $data['email']    = $email;
            $data['model']    = $model;
            $data['city']     = $this->cityInfo['id'];
            \app\common\model\User::event('after_insert',function($obj){
                $info_data = [];
                $obj->userInfo()->save($info_data);
                $store['user_id'] = $obj->id;
                $store['title']   = $obj->nickname.'的店铺';
                model('store')->save($store);
            });
            if($this->mod->save($data)){
                $data['id'] = $this->mod->id;
                unset($data['password']);
                cookie('userInfo',$data);
                $return['status'] = 1;
                $return['msg']    = '恭喜您！注册成功！';
                $return['uri']    = url('user.index/index');
            }else{
                $return['msg']    = '注册失败';
            }
        }
        return json($return);
    }
    public function pass(){
        if(request()->isPost()){
            $email    = input('post.email');
            $mobile   = input('post.mobile');
            $code     = input('post.code');
            $password = input('post.password');
            $verfiy_code = cookie('findpass');
            $verfiy_arr  = explode('|',$verfiy_code);
            $verfiy      = $verfiy_arr[0];
            $timesend    = $verfiy_arr[1];
            $return['status'] = 0;
            if($this->checkUser($email,'email')){
                $return['msg'] = '邮箱不存在';
            }elseif($this->checkUser($mobile,'mobile')){
                $return['msg'] ='手机号码不存在';
            }if($code!=$verfiy){
                $return['msg'] = '验证码不正确';
            }elseif(time()-$timesend>300){
                $return['msg'] = '验证码已过期，请重新获取!';
            }else{
                $where['email']   = $email;
                $where['mobile']  = $mobile;
                $edit['password'] = $password;
                if(model('user')->save($edit,$where)){
                    $return['status'] = 1;
                    $return['msg']    = '密码重置成功，请登录';
                    $return['uri']    = url('user.login/index');
                }else{
                    $return['msg']    = '密码重置失败，请联系网站客服';
                }
            }
            return json($return);
        }else{
            $this->setSeo(['title'=>'找回密码']);
            $this->assign('title','找回密码');
            return $this->fetch();
        }
    }
    //发送验证码
    public function getEmailCode(){
        $email  = input('post.email');
        $mobile = input('post.mobile');
        $return['status'] = 0;
        if($this->checkUser($email,'email')){
            $return['msg'] = '邮箱不存在';
        }elseif($this->checkUser($mobile,'mobile')){
            $return['msg'] = '手机号码不存在';
        }else{
            //发送验证邮件
            $verfiy = codestr(6);
            cookie('findpass',$verfiy.'|'.time());
            $html = '您正在执行找回密码操作，您的验证码为:'.$verfiy.',请在5分钟内输入。';
            if(sendEmail($email,$html)){
               $return['status'] = 1;
                $return['msg']   = '邮件发送成功，请注意查收';
            }else{
                $return['msg']   = '邮件发送失败，请联系网站客服';
            }
        }
        return json($return);
    }
    //验证 验证码
    public function ajaxcheckCode(){
        $code = input('get.code');
        $verfiy_code = cookie('findpass');
        $verfiy_arr  = explode('|',$verfiy_code);
        $verfiy      = $verfiy_arr[0];
        $timesend    = $verfiy_arr[1];
        $return['status'] = 0;
        if($code!=$verfiy){
            $return['msg'] = '验证码不正确';
        }elseif(time()-$timesend>300){
            $return['msg'] = '验证码已过期，请重新获取!';
        }else{
            $return['status'] = 1;
            cookie('findpass',null);
        }
        return json($return);
    }
    //第三方登录
    public function login($type=null){
        if($type){
            $sns = \loginsdk\ThinkOauth::getInstance($type);
            header("Location:".$sns->getRequestCodeURL());
        }else{
            $this->redirect('index');
        }
    }
    public function callback($type = null, $code = null) {
        header("Content-type: text/html; charset=utf-8");
        (empty($type) || empty($code)) && $this->error('参数错误');
        $sns = \loginsdk\ThinkOauth::getInstance($type);

        //腾讯微博需传递的额外参数
        $extend = null;
        if ($type == 'tencent') {
            $extend = ['openid' => input('get.openid'), 'openkey' => input('get.openkey')];
        }
        $tokenArr = $sns->getAccessToken($code, $extend);
        $openid = trim($tokenArr['openid']);
        $token = trim($tokenArr['access_token']);
        if ($openid) {
            cookie('openid',$openid);
            cookie('token',$token);
            $sdk['openid'] = $openid;
            $sdk['access_token'] = $token;
            $field = strtolower($type).'_openid';
            $sdk['field'] = $field;
            $data[$field] = $openid;
            cookie('sdkInfo',$sdk);
            cookie("access_token", $token);
            $info = $this->mod->where($data)->field('username,nickname,mobile,model,status,email,id')->find();
            if ($info) { //若是有该账号就登录
                $edit['login_time'] = time();
                $edit['login_ip']   = request()->ip();
                $edit['login_num']  = ['exp','login_num+1'];
                $this->mod->save($edit,['id'=>$info['id']]);
                $model = $info->getData('model');
                $info = objToArray($info);
                $info['model'] = $model;
                cookie('userInfo',$info);
                $this->success('登陆成功',url('user.index/index'));
            } else { //没有的话绑定
                $user = cookie('userInfo');
                $user_id  = $user['id'];
                $username = $user['username'];
                if ($user_id && $username) { //用户已登录，自动绑定
                    $res = $this->mod->save([$field=>$openid],['id'=>$info['id']]);
                    //绑定账号
                    if($res){
                        $this->success("绑定成功！", url('user.index/index'));
                    }else{
                        $this->error("绑定失败！", url('user.index/index'));
                    }
                } else { //用户未登录，跳转到绑定页面
                    if ($field == 'qq') { //针对新版qq互联在绑定页，要显示昵称，否则不通过***
                        $data = $sns->call('user/get_user_info');
                        $nickname = $data['nickname'];
                    } else {
                        $userinfo = $sns->$type($tokenArr);
                        $nickname = $userinfo['name'];
                    }
                    cookie('nickname', $nickname);
                    $this->redirect("user.login/bind");
                }
            }
        } else {
            $this->error('系统出错，请稍后再试！',url('user.login/index'));
        }
    }
    public function bind(){
        $nickname = cookie('nickname');
        $assignArr = array(
            "title" => "绑定账号",
            "nickname" => $nickname
        );
        if(request()->isPost()){
            $verify_code = input('post.verfiy');
            if(!captcha_check($verify_code)){
                $this->error('验证码不正确');
            }
            $username = input('post.username','');
            $password = input('post.password','');
            if(empty($username) || empty($password)){
                $this->error('请填写用户名或密码');
            }
            $map['username|email'] = $username;
            $info = $this->mod->where($map)->field('username,nickname,mobile,model,status,email,id,password')->find();
            $sdkInfo  =  cookie('sdkInfo');
            $field    = $sdkInfo['field'];
            $openid   =  $sdkInfo["openid"];
            $data[$field] = $openid;
            if($info){//绑定账号
                if($info['password'] == passwordEncode($password)){
                    unset($info['password']);
                    $edit['login_time'] = time();
                    $edit['login_ip']   = request()->ip();
                    $edit['login_num']  = ['exp','login_num+1'];
                    $edit[$field] = $openid;
                    $this->mod->save($edit,['id'=>$info['id']]);
                    $model = $info->getData('model');
                    $info = objToArray($info);
                    $info['model'] = $model;
                    cookie('userInfo',$info);
                    $this->success('绑定成功',url('user.index/index'));
                }else{
                    $this->error('密码不正确');
                }
            }else{
                //注册账号
                $data['username']  = $username;
                $data['nickname']  = $nickname;
                $data['password']  = $password;
                $data['status'] = 1;
                $data[$field]      = $openid;
                if($this->mod->save($data)){
                    $info_data = [];
                    $this->mod->userInfo()->save($info_data);
                    $store['user_id'] = $this->mod->id;
                    $store['title']   = $nickname.'的店铺';
                    model('store')->save($store);
                    $data['model'] = 1;
                    $data['id']    = $this->mod->id;
                    $data['email'] = '';
                    $data['mobile'] = '';
                    unset($data['password']);
                    cookie('userInfo',$data);
                    $this->success('注册成功,正为您转向会员中心',url('user.index/index'));
                }
            }
        }
        $this->assign($assignArr);
        return $this->fetch();
    }
    //退出录
    public function logout(){
        cookie('userInfo',null);
        $this->redirect('Index/index');
    }
    public function ajaxCheckUser(){
        $username = input('get.username');
        $mobile   = input('get.mobile');
        $email    = input('get.email');
        $return['status'] = 0;
        if($username){
            if($this->checkUser($username)){
                $return['status'] = 1;
            }
        }
        if($mobile){
            if($this->checkUser($mobile,'mobile')){
                $return['status'] = 1;
            }
        }
        if($email){
            if($this->checkUser($email,'email')){
                $return['status'] = 1;
            }
        }
        return json($return);
    }
    private function checkUser($val,$field='username'){
        $where[$field] = $val;
        $count = $this->mod->where($where)->count();
        if($count==0){
            return true;
        }else{
            return false;
        }
    }
}